﻿
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;

namespace Stanza.Silverlight.Media
{
    public static class ColorTools
    {
        public const byte Opaque = Byte.MaxValue;

        private static Regex hexRegex = new Regex( @"^#?([0-9a-f]{2}){3,4}$", RegexOptions.IgnoreCase );

        public static byte ParseHexValue( string byteText )
        {
            byte result;
            if( !Byte.TryParse( byteText, System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture, out result ) )
                result = 0;
            return result;
        }

        public static string ConvertColorToString( Color colorValue )
        {
            string colorText;
            if( colorValue.A == Opaque )
                colorText = String.Format( "#{0:x02}{1:x02}{2:x02}", colorValue.R, colorValue.G, colorValue.B );
            else
                colorText = String.Format( "#{0:x02}{1:x02}{2:x02}{3:x02}", colorValue.A, colorValue.R, colorValue.G, colorValue.B );
            return colorText.ToUpper();
        }

        public static Color ConvertStringToColor( string colorText )
        {
            colorText = colorText.Trim();
            Color colorValue = Colors.Black;
            Match m;
            if( ( m = hexRegex.Match( colorText ) ).Success )
            {
                bool includesAlpha = ( m.Groups[1].Captures.Count == 4 );
                int startIdx = includesAlpha ? 1 : 0;
                colorValue = new Color();
                colorValue.A = includesAlpha ? ParseHexValue( m.Groups[1].Captures[0].Value ) : Opaque;
                colorValue.R = ParseHexValue( m.Groups[1].Captures[startIdx].Value );
                colorValue.G = ParseHexValue( m.Groups[1].Captures[startIdx + 1].Value );
                colorValue.B = ParseHexValue( m.Groups[1].Captures[startIdx + 2].Value );
            }
            return colorValue;
        }

        public static bool IsValidColorString( string colorText )
        {
            colorText = colorText.Trim();
            return ( hexRegex.IsMatch( colorText ) );
        }
    }
}
